<template>
	<div ref="container" class="lottie-container" />
</template>

<script setup lang="ts">
import lottie from "lottie-web";

const props = defineProps<{
	path: string;
	loop?: boolean;
	autoplay?: boolean;
	speed?: number;
}>();

const container = ref<HTMLElement | null>(null);
let animation: any = null;

const loadAnimation = async () => {
	if (!container.value) return;

	try {
		const response = await fetch(props.path);
		const animationData = await response.json();

		if (animation) {
			animation.destroy();
		}

		animation = lottie.loadAnimation({
			container: container.value,
			renderer: "svg",
			loop: props.loop ?? false,
			autoplay: props.autoplay ?? true,
			animationData,
		});

		if (props.speed) {
			animation.setSpeed(props.speed);
		}
	} catch (error) {
		console.error("Failed to load Lottie animation:", error);
	}
};

watch(() => props.path, loadAnimation);

onMounted(loadAnimation);

onBeforeUnmount(() => {
	if (animation) {
		animation.destroy();
	}
});

// 暴露动画实例方法
defineExpose({
	play: () => animation?.play(),
	stop: () => animation?.stop(),
	pause: () => animation?.pause(),
	goToAndPlay: (value: number) => animation?.goToAndPlay(value, true),
	goToAndStop: (value: number) => animation?.goToAndStop(value, true),
	setSpeed: (speed: number) => animation?.setSpeed(speed),
	getDuration: () => animation?.getDuration(true),
});
</script>

<style scoped>
.lottie-container {
	width: 100%;
	height: 100%;
}
</style>
